package com.zengqingfa.thread.demo6;

/**
 * @fileName: DeadLock
 * @author: zengqf3
 * @date: 2020-10-7 19:55
 * @description:
 */
//死锁 多个线程互相持有对方需要的资源，然后形成僵持
public class DeadLock {

    public static Object obj1 = new Object();
    public static Object obj2 = new Object();

    public static void main(String[] args) {
        new Thread(new Lock1()).start();
        new Thread(new Lock2()).start();
    }

}

class Lock1 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (DeadLock.obj1) {
                System.out.println("获得obj1的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (DeadLock.obj2) {
                    System.out.println("获得obj2的锁");
                }
            }
        }
    }
}

class Lock2 implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (DeadLock.obj2) {
                System.out.println("获得obj2的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (DeadLock.obj1) {
                    System.out.println("获得obj1的锁");
                }
            }
        }
    }
}


